package com.study.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.entity.Clazz;
import com.study.entity.ClazzQueryParam;
import com.study.entity.InfoCount;
import com.study.entity.PageBean;
import com.study.mapper.ClazzMapper;
import com.study.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    public void setStatus(Clazz clazz) {
        if (LocalDate.now().isBefore(clazz.getBeginDate())) {
            clazz.setStatus("未开班");
        } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
            clazz.setStatus("已结课");
        } else {
            clazz.setStatus("在读");
        }
    }

    @Override
    public PageBean list(ClazzQueryParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Clazz> clazzes = clazzMapper.list(param);
        for (Clazz clazz : clazzes) {
            setStatus(clazz);
        }
        Page pages = (Page) clazzes;
        long total = pages.getTotal();
        List rows = pages.getResult();
        PageBean pageBean = new PageBean(total, rows);
        return pageBean;
    }

    @Override
    public void delete(Integer id) {
        clazzMapper.delete(id);
    }

    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getByid(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> selectAll() {
      List<Clazz>  clazzes = clazzMapper.selectAll();
      return  clazzes;
    }

    @Override
    public Map<String, Object[]> countNum() {
        Map<String,Object[]> map = new HashMap<>();
       List<InfoCount> list = clazzMapper.countNum();
       int length = list.size();
       String[] names = new String[length];
       Integer[] counts = new Integer[length];
       int i = 0;
        for (InfoCount infoCount : list) {
            names[i]=(String) infoCount.getInfo();
            counts[i]=infoCount.getCount();
            i++;
        }
        map.put("clazzList",names);
        map.put("dataList",counts);
        return map;
    }

}
